import {getUserInfo,} from "../api/home/index.js"
import {updateUser,getHeadImgUploadConfig} from "../api/personal/index.js"
export default {
	data() {
		return {
			nickname: '',
			name: '',
			headImgUrl: '',
			phoneNumber: '',
			popShows:false,
		}
	},
	onReady() {
		this.fetchSomething()
	},
	onShow(){
		this.fetchSomething()
	},
	onPullDownRefresh(){//页面下拉刷新
		this.fetchSomething()
		uni.stopPullDownRefresh();
	},
	methods: {
		async fetchSomething(query){
			this.getUser()
		},
		async getUser() {
			let res = await getUserInfo()
			let data = res.data || {}
			this.nickname = res.data.nickname
			this.headImgUrl = res.data.headImgUrl
			this.phoneNumber = res.data.phoneNumber
			uni.setStorageSync('userInfo',data)
		},
		open() {
			this.popShows = true
		},
		close() {
			this.popShows = false
		},
		go(url, item) {
			uni.navigateTo({
				url: `${url}`
			})
		},
		async handleUpdateUser() {
			this.nickname = this.name
			let res = await updateUser({
				nickname: this.nickname
			})
			this.name = null
			this.popShows = false
			this.getUser()
		},
		handleAvatar() {
			uni.chooseImage({
				count: 1, //默认9
				sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
				sourceType: ['album'], //从相册选择
				success: async(res) => {
					let img = res.tempFilePaths[0]
					console.log('res.tempFilePaths',res.tempFilePaths)
					let _res = await getHeadImgUploadConfig()
					let data = _res.data || {}
					let key = data.key;
					uni.showLoading({
						title: '图片上传中'
					})
					uni.uploadFile({
						url: "https://up.qiniup.com/", //华东地区上传
						filePath: img,
						name: 'file',
						method: "POST",
						formData: {
							'key': key, //key值
							'token': data.token //七牛云token值
						},
						success: async uploadFileRes => {
							//uploadFileRes 返回了data是一个json字符串 
							//拿到里面的key拼接上域名，再反出去就ok了
							let strToObj = JSON.parse(uploadFileRes
									.data),
								backUrl = data.baseUrl +
								strToObj.key;
							console.log("backUrl", backUrl)
							let ress = await updateUser({
								headImgUrl: backUrl
							})	
							this.getUser()
							uni.hideLoading();
						},
						fail: fail => {
							uni.showToast({
								title: "网络错误",
								icon: "none"
							});
							uni.hideLoading();
						}
					})


				}
			});
		}
	},

}